<template>
  <div class="view-container">
    <div class="filter-container">
      <el-row :gutter="40">
        <el-form :inline="true" :model="queryParams" label-position="right" size="small" class="filter-form-inline">
          <el-row :gutter="40" style="margin-left: 20px; margin-right: 0px">
            <el-col :span="5">
              <el-form-item label="终端类型" style="width: 100%">
                <el-select v-model="queryParams.terminalType" clearable style="width: 100%" placeholder="请选择终端类型">
                  <el-option v-for="item in terminalData.filter(a=>a.value !== 'all')" :key="item.id"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="终端所在地" style="width: 100%">
                <el-cascader v-model="value" :popper-append-to-body="false" style="width:100%" placeholder="请选择终端所在地区"
                  :options="cityList" :props="{ value:'regionCode',label:'regionName', expandTrigger: 'hover' }"
                  @change="handlCity" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="营销区域" style="width: 100%">
                <el-cascader v-model="saleValue" :popper-append-to-body="false" style="width:100%"
                  placeholder="请选择终端所属营销区域" :options="salesArea"
                  :props="{checkStrictly: true, value:'id',label:'salesAreaName' }" @change="handlArea" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="关键字" style="width: 100%">
                <el-input v-model="queryParams.selectStr" clearable placeholder="输入编号、名称、地区、详细地址" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item style="width: 100%">
                <el-button class="border-btn" @click="handlReset">重置
                </el-button>
                <el-button type="primary" class="main-btn" @click="handlSearch">搜索
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </div>
    <div class="main-content" style="padding-top: 0">
      <div class="list-container">
        <table-tools>
          <template #left>
            <el-button class="main-btn" v-auth="{v:['crm:baseInfo:terminal:create']}" size="small" type="primary"
              @click="handlNew">新建
            </el-button>
          </template>
        </table-tools>
        <table-view :data="tableData" header-cell-class-name="table-header" size="medium" border :cell-style="cellStyle"
          @sort-change="handlSort" @row-click="aloneClick">
          <el-table-column prop="terminalNo" :min-width="140" label="终端编号" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column prop="terminalName" :min-width="160" label="终端名称" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column prop="terminalType" :min-width="120" label="终端类型" align="center"
            :show-overflow-tooltip="true">
            <template #default="{row}">
              {{ getLabel('app_mode', row.terminalType) }}
            </template>
          </el-table-column>

          <el-table-column label="所在地区" :min-width="180" header-align="center" :show-overflow-tooltip="true">
            <template #default="{row}">
              <span v-if=" row.provinceName">{{row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="address" label="详细地址" :min-width="180" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column prop="saleAreaName" label="所属营销区域" :min-width="180" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column prop="createdAt" label="创建时间" sortable="custom" :min-width="180" align="center"
            :show-overflow-tooltip="true">
            <template #default="{row}">
              {{ dateFormat("yyyy-mm-dd HH:MM:SS",row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column prop="terminalStatus" :min-width="120" label="终端状态" align="center"
            :show-overflow-tooltip="true" fixed="right">
            <template #default="{row}">
              <div v-if="row.terminalStatus === '1' || row.terminalStatus === '2' ">潜在终端</div>
              <div v-if="row.terminalStatus === '4' || row.terminalStatus === '5' ">交易终端</div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" :min-width="120" fixed="right">
            <template #default="{row}">
              <el-button type="text" v-auth="{v:['crm:baseInfo:terminal:change']}" @click="handlEdit(row.id)">变更信息
              </el-button>
            </template>

          </el-table-column>
        </table-view>
        <Pagination v-model:page="queryParams.page" v-model:limit="queryParams.pageSize"
          style="display: flex; justify-content: flex-end" :total="total" @pagination="handlList" />
      </div>
    </div>

    <rule-form ref="ruleFormDialog" :type-str="typeStr" :sub="sub" form-type="1" @succsess="succsess" />
    <registered ref="registeredDialog" />
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { crmStore } from "@CRM/store";
import area from "@/utils/area";

export default {
  name: "Index",
  components: {
    ruleForm: defineAsyncComponent(() =>
      import("@CRM/views/marketing/customer/terminal/modules/ruleForm.vue")
    ),
    registered: defineAsyncComponent(() =>
      import("@CRM/views/marketing/customer/terminal/modules/registered.vue")
    ),
  },
  setup() {
    const api = inject("api");
    const router = useRouter();
    const route = useRoute();
    // 搜索对象
    var data = reactive({
      queryParams: {
        terminalType: "",
        status: "",
        provinceCode: [],
        cityCode: [],
        areaCode: [],
        saleAreaId: 0,
        selectStr: "",
        pageSize: 20,
        page: 1,
        createdSort: "",
      },
      value: [],
      saleValue: [],
      tableData: [],
      total: 0,
      typeStr: "create",
      ruleFormDialog: null,
      registeredDialog: null,
      terminalData:
        crmStore.getters["dictionary/getDictionary"]["app_mode"] || [],
      terminalStatusData:
        crmStore.getters["dictionary/getDictionary"]["terminal_status"] || [],
      salesArea: [],
      cityList: area,
      sub: {
        boole: true,
        title: "保存",
      },
    });
    const currentInstance = getCurrentInstance();

    const handlSalesArea = () => {
      api.terminal.TERMINAL_TREE().then((res) => {
        if (res.code === 0) {
          data.salesArea = res.data;
        }
      });
    };

    const handlArea = (val) => {
      data.queryParams.saleAreaId = val[val.length - 1];
    };

    const handlCity = (val) => {
      if (val) {
        data.queryParams.provinceCode = [val[0]];
        data.queryParams.cityCode = [val[1]];
        data.queryParams.areaCode = [val[2]];
      }
    };

    // 新建表单
    const handlNew = () => {
      data.typeStr = "create";
      data.ruleFormDialog.open(null, 1);
    };

    // 获取列表
    const handlList = () => {
      api.terminal.TERMINAL_LIST(data.queryParams).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    };

    // 编辑
    const handlEdit = (id) => {
      data.typeStr = "editor";
      data.sub = {
        boole: false,
        title: "保存",
      };
      data.ruleFormDialog.open(id, 2);
    };

    // 删除
    const handlDele = (id) => {
      currentInstance.proxy
        .alertBox({
          message: "是否确认删除该终端？",
          title: "终端删除",
        })
        .then(() => {
          api.terminal.TERMINAL_DELETE(id).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            } else {
              handlList();
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    // 刷新列表
    const succsess = () => {
      handlList();
    };

    // 重置表格
    const handlReset = () => {
      data.queryParams = {
        terminalType: "",
        status: "",
        provinceCode: [],
        cityCode: [],
        areaCode: [],
        saleAreaId: 0,
        selectStr: "",
        pageSize: 20,
        page: 1,
      };
      data.value = [];
      data.saleValue = [];
      handlList();
    };

    // 搜索表格
    const handlSearch = () => {
      data.queryParams.page = 1;
      handlList();
    };

    // 单机表格
    const aloneClick = (row, column, event) => {
      if (column.label === "操作") return;
      router.push({
        path: "/baseInfo/baseInfoTerminal/baseInfoTerminalDetail",
        query: { id: row.id },
      });
    };

    // 鼠标样式
    const cellStyle = () => {
      return "cursor:pointer;";
    };

    // 注册 终端
    const handlTo = (row) => {
      data.registeredDialog.open(row, null);
    };

    // 排序
    const handlSort = (row) => {
      if (row.column) {
        if (row.column.label === "创建时间") {
          switch (row.order) {
            case "ascending":
              data.queryParams.createdSort = "asc";
              break;
            case "descending":
              data.queryParams.createdSort = "desc";
              break;
          }
        }
      }
      handlList();
    };

    //* *******************
    onMounted(() => {
      handlList();
      handlSalesArea();
      if (route.query.type === "direct") {
       setTimeout(()=>{
         handlNew()
       },1000)
      }
    });
    //* *******************

    return {
      ...toRefs(data),
      handlNew,
      handlReset,
      handlSearch,
      aloneClick,
      cellStyle,
      handlList,
      succsess,
      handlTo,
      handlEdit,
      handlDele,
      handlSalesArea,
      handlArea,
      handlCity,
      handlSort,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>